package com.moweilin.hello_server;

import io.vertx.core.Vertx;
import io.vertx.core.http.HttpMethod;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.StaticHandler;
import io.vertx.ext.web.handler.TemplateHandler;
import io.vertx.ext.web.handler.sockjs.*;
import io.vertx.ext.web.templ.TemplateEngine;
import io.vertx.ext.web.templ.ThymeleafTemplateEngine;

import java.text.DateFormat;
import java.util.Date;

/**
 * Created by moweilin on 2016/4/20.
 */
public class ServerApp {
    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            System.out.println("Shutdown server");
            vertx.close();
        }));
        Router router = Router.router(vertx);

        router.route("/").handler(new HelloHandler());
        router.route("/head/").handler(new HeadHandler());
        router.route("/form").handler(BodyHandler.create());
        router.route("/form").handler(new FormHandler());

        /** web sockert */
        BridgeOptions options = new BridgeOptions().addOutboundPermitted(new PermittedOptions().setAddress("news-feed"));

        router.route("/eventbus/*").handler(SockJSHandler.create(vertx).bridge(options, event -> {

            // You can also optionally provide a handler like this which will be passed any events that occur on the bridge
            // You can use this for monitoring or logging, or to change the raw messages in-flight.
            // It can also be used for fine grained access control.

            if (event.type() == BridgeEventType.SOCKET_CREATED) {
                System.out.println("A socket was created");
            }

            // This signals that it's ok to process the event
            event.complete(true);

        }));
        vertx.setPeriodic(1000, t -> vertx.eventBus().publish("news-feed", DateFormat.getDateTimeInstance().format(new Date())));
        ThymeleafTemplateEngine engine = ThymeleafTemplateEngine.create();
        TemplateHandler templateHandler = TemplateHandler.create(engine);
        router.route(HttpMethod.GET,"/pages/*").handler(templateHandler);

        router.route("/static/*").handler(StaticHandler.create());
        vertx.createHttpServer()
                .requestHandler(router::accept)
                .listen(8080, handler -> {
                    if (handler.succeeded()) {
                        System.out.println("http://localhost:8080/");
                    } else {
                        System.err.println("Failed to listen on port 8080");
                    }
                });

    }
}
